package com.achun.getcouponleague.ui.custom;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.achun.getcouponleague.R;
import com.achun.getcouponleague.utils.Logutils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

public class FlowTextLayout extends ViewGroup {
    //定义间距
    public static final int DEFAULT_SPACE = 10;
    private float mItemHorizontalSpace = DEFAULT_SPACE;
    private float mItemVerticalSpace = DEFAULT_SPACE;
    private List<String> textList = new ArrayList<>();
    private int mSelfWidth;

    public float getmItemHorizontal() {
        return mItemHorizontalSpace;
    }

    public void setmItemHorizontal(float mItemHorizontal) {
        this.mItemHorizontalSpace = mItemHorizontal;
    }

    public float getmItemVerticalSpace() {
        return mItemVerticalSpace;
    }

    public void setmItemVerticalSpace(float mItemVerticalSpace) {
        this.mItemVerticalSpace = mItemVerticalSpace;
    }

    public FlowTextLayout(Context context) {
        this(context, null);
    }

    public FlowTextLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public FlowTextLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        //去拿到相关属性
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.FlowTextStyle);
        mItemHorizontalSpace = ta.getDimension(R.styleable.FlowTextStyle_horizontalspace, DEFAULT_SPACE);
        mItemVerticalSpace = ta.getDimension(R.styleable.FlowTextStyle_verticalspace, DEFAULT_SPACE);
        ta.recycle();
    }

    public void setTextList(List<String> textList) {
        if (textList==null||textList.size()==0){
            return;
        }
        removeAllViews();
        this.textList.clear();
        this.textList.addAll(textList);
        Collections.reverse(this.textList);
        Logutils.e(this.getClass(),"瀑布布局有数据--"+textList);
        //遍历内容，添加子view
        for (String text : this.textList) {
            TextView item = (TextView) LayoutInflater.from(getContext()).inflate(R.layout.text_flow_item, this, false);
            item.setText(text);
            item.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    onFlowItemClickListener.onItemclick(text);
                }
            });
            addView(item);

        }
    }


    List<List<View>> lines = new ArrayList<>();

    @Override//这个测量方法会运行不止一次
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        //没有数据就不用测量了
        if(getChildCount()==0)return;
        lines.clear();
        List<View> line = null;
        Logutils.e(this.getClass(), "测量。。。");
        //获取父控件宽度
        mSelfWidth = MeasureSpec.getSize(widthMeasureSpec) - getPaddingLeft() - getPaddingRight();
        int childCount = getChildCount();
        Logutils.e(this.getClass(), "子控件个数--》" + childCount);
        for (int i = 0; i < childCount; i++) {
            //对子view进行测量
            TextView childView = (TextView) getChildAt(i);
            Logutils.e(this.getClass(), "测量前" + childView.getMeasuredWidth());
            measureChild(childView, widthMeasureSpec, heightMeasureSpec);
            Logutils.e(this.getClass(), "测量后" + childView.getMeasuredWidth());
            if (line == null) {
                line = new ArrayList<>();
                line.add(childView);
                lines.add(line);
            } else {
                //判断是否可以继续添加
                if (canAddView(childView, line)) {
                    line.add(childView);
                } else {
                    line=new ArrayList<>();
                    line.add(childView);
                    lines.add(line);
                    Logutils.e(this.getClass(), "行内个数--》" + line.size());
                }
            }
        }
        int mSelfHeight = (int) (lines.size() * (mItemHorizontalSpace + getChildAt(0).getMeasuredHeight()) + (int) mItemVerticalSpace);
        Logutils.e(this.getClass(), "父宽度为" + mSelfWidth + "父高度为--》" + mSelfHeight);
        //测量自己
        setMeasuredDimension(mSelfWidth, mSelfHeight);
        Logutils.e(this.getClass(), "行数为--》" + lines.size());
    }

    /*判断是否可以继续添加子控件*/
    private boolean canAddView(TextView childView, List<View> line) {
        //如果行内子控件的总宽度+(line.size()+1)*间隙+新添加的childview的宽度小于等于屏幕宽度，那就可以添加
        int totalWidth=0;
        for (View view : line) {
            totalWidth+=view.getMeasuredWidth();
        }
        if (totalWidth+(line.size()+1)*mItemHorizontalSpace+childView.getMeasuredWidth()<= mSelfWidth) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    protected void onLayout(boolean b, int i, int i1, int i2, int i3) {
        Logutils.e(this.getClass(), "layout布局了行数为--》"+lines.size());
//摆放孩子
        int spacetotop=getPaddingTop();
        //layout参数（左，上，右，下）离原点的距离
        for (int i4 = 0; i4 < lines.size(); i4++) {
            int spacetoleft= getPaddingLeft();
            List<View> lineview = lines.get(i4);
            Logutils.e(this.getClass(),"布局行数--》"+i4);
            for (int i5 = 0; i5 < lineview.size(); i5++) {
                TextView view = (TextView) lineview.get(i5);
                view.layout(spacetoleft,spacetotop,spacetoleft+view.getMeasuredWidth(),spacetotop+view.getMeasuredHeight());
                Logutils.e(this.getClass(),"布局每一个》"+i5+view.getText().toString());
                spacetoleft+=view.getMeasuredWidth()+mItemHorizontalSpace;
                Logutils.e(this.getClass(),"宽度为》"+spacetoleft);
            }
            spacetotop+=getChildAt(0).getMeasuredHeight()+mItemHorizontalSpace;

        }

    }
    public OnFlowItemClickListener onFlowItemClickListener;
    public interface OnFlowItemClickListener{
        void onItemclick(String item);
    }
    public void setOnFlowItemClickListener(OnFlowItemClickListener onFlowItemClickListener){
        this.onFlowItemClickListener=onFlowItemClickListener;
    }
}
